package controller

import (
	"fmt"
	"gin/common"
	"gin/model"
	"gin/util"
	"log"

	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
)

func isTelExist(db *gorm.DB, tel string) bool {
	user := &model.User{}
	//users := make([]*User, 0, 0)
	err := db.Model(user).Where("tel=?", tel).Limit(1).Find(user).Error
	fmt.Println(err, user)

	if user.ID > 0 {
		return true
	}

	return false
}

func Register(ctx *gin.Context) {
	db := common.GetDb()
	name := ctx.PostForm("name")
	tel := ctx.PostForm("tel")
	password := ctx.PostForm("password")
	//验证数据
	if len(tel) != 11 {
		ctx.JSON(422, gin.H{
			"code": 422,
			"msg":  "手机号必须为11位",
		})
	}
	if len(password) < 6 {
		ctx.JSON(422, gin.H{
			"code": 422,
			"msg":  "密码不小于6位",
		})
	}

	if len(name) == 0 {
		name = util.RandomString(10)
	}

	log.Println(name, tel, password)

	//判断手机号
	if isTelExist(db, tel) {
		ctx.JSON(422, gin.H{"code": 200, "msg": "手机号不能重复"})
		return
	}

	hashedPwd, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		ctx.JSON(500, gin.H{"code": 500, "msg": "加密出错"})
		return
	}
	//创建用户
	newUser := model.User{
		Name:     name,
		Tel:      tel,
		Password: string(hashedPwd),
	}

	db.Create(&newUser)
	//返回结果
	ctx.JSON(200, gin.H{"code": 200, "msg": "注册成功"})
}

func Login(ctx *gin.Context) {
	//接收参数
	db := common.GetDb()
	tel := ctx.PostForm("tel")
	password := ctx.PostForm("password")

	if len(tel) != 11 {
		ctx.JSON(422, gin.H{
			"code": 422,
			"msg":  "手机号必须为11位",
		})
	}

	if len(password) < 6 {
		ctx.JSON(422, gin.H{
			"code": 422,
			"msg":  "密码不小于6位",
		})
	}

	//验证用户是否存在
	var user model.User
	db.Where("tel=?", tel).First(&user)
	if user.ID == 0 {
		ctx.JSON(200, gin.H{"code": 422, "msg": "用户不存在"})
	}
	//验证密码
	if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
		ctx.JSON(200, gin.H{"code": 422, "msg": "密码错误"})
	}
	//发放token
	token, err := common.ReleaseToken(user)
	if err != nil {
		ctx.JSON(433, gin.H{
			"code": 500,
			"msg":  "生成token失败",
		})
		log.Println("token 生成失败")
		log.Println(err)
		return
	}

	ctx.JSON(200, gin.H{"code": 200, "msg": "登录成功", "data": gin.H{
		"token": token,
	}})
}

func Info(c *gin.Context) {
	user, _ := c.Get("user")
	c.JSON(200, gin.H{"code": 200, "user": user})
}
